import json
import logging
from random import randint

from google.appengine.ext import ndb
from google.appengine.api import memcache
from constants import MAX_PIN_LENGTH, MIN_PIN_LENGTH


class Player(ndb.Model):
    """ stores users name and words for a player
    args:
        email: (ndb.StringProperty())
        words: (ndb.StringProperty(repeated = True))
        pin_code: (ndb.IntegerProperty())
    """
    cache_prefix = 'player_by_email_'

    game_keys = ndb.StringProperty(repeated=True)
    game_names = ndb.StringProperty(repeated=True)
    game_pins = ndb.IntegerProperty(repeated=True)
    email = ndb.StringProperty()
    nickname = ndb.StringProperty(indexed=False)
    words = ndb.StringProperty(repeated=True, indexed=False)
    pin_code = ndb.IntegerProperty(indexed=False)

    def __init__(self, **kwargs):
        super(Player, self).__init__(**kwargs)
        self.pin_code = randint(10 ** (MIN_PIN_LENGTH - 1),
                                10 ** MAX_PIN_LENGTH - 1)

    def make_json(self):
        all_json = {
            u'email': email,
            u'nickname': nickname,
            u'words': [],
        }
        for word in self.words:
            all_json[u'words'].append({u'text': word, u'owner': email})
        return unicode(json.dumps(all_json, sort_keys=True).encode("utf-8"))

    @staticmethod
    def get_by_email(player_email):
        player_key = memcache.get(Player.cache_prefix + str(player_email))
        if player_key is not None:
            player = player_key.get()
        else:
            query_result = Player().query().filter(Player.email ==
                                                   player_email)
            player = query_result.get()
            if player is None:
                return None
            memcache.set(Player.cache_prefix + str(player_email), player.key)
        return player

    def put(self):
        super(Player, self).put()
        memcache.set(Player.cache_prefix + str(self.email), self.key)
